package com.peoit.honeycomb.controller;


import com.peoit.honeycomb.application.SecurityApplication;
import com.peoit.honeycomb.domain.User;
import com.peoit.honeycomb.dto.security.PermissionDto;
import com.peoit.honeycomb.utils.CipherUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.logging.Logger;

/**
 * Created by Bing.Zeng on 2015/9/22.
 */
@Controller
@RequestMapping("/")
public class IndexController  extends  HoneycombBaseController {
	Logger logger = Logger.getLogger(IndexController.class.getName());
	@Autowired
	SecurityApplication securityApplication;

	/**
	 *    index page
	 */
	@RequestMapping(value = "/")
	public ModelAndView index(){
		return new ModelAndView("login");
	}

	/**
	 *    index page
	 */
	@RequestMapping(value = "/login")
	public ModelAndView login(){
		return new ModelAndView("login");
	}


	/**
	 * 登陆
	 * @param username
	 * @param password
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/login",method = RequestMethod.POST )
	public ModelAndView logint(String username,String password,ModelMap modelMap){

		if(StringUtils.isBlank(username)){
			modelMap.addAttribute("message_login", "用户名不能为空！！");
			return view("login");
		}
		if(StringUtils.isBlank(password)){
			modelMap.addAttribute("message_login", "密码不能为空！！");
			return view("login");
		}


//		String passwords = CipherUtil.generatePassword(password);
		String passwords =  password;

		UsernamePasswordToken token = new UsernamePasswordToken(username, passwords);
		token.setRememberMe(true);
		System.out.println("为了验证登录用户而封装的token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
		//获取当前的Subject
		Subject currentUser = SecurityUtils.getSubject();
		try {
			//在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
			//每个Realm都能在必要时对提交的AuthenticationTokens作出反应
			//所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
			System.out.println("对用户[" + username + "]进行登录验证..验证开始");
			currentUser.login(token);
			System.out.println("对用户[" + username + "]进行登录验证..验证通过");

		}catch(UnknownAccountException uae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
			modelMap.addAttribute("message_login", "未知账户");
			return view("login");
		}catch(IncorrectCredentialsException ice){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
			modelMap.addAttribute("message_login", "密码不正确");
			return view("login");
		}catch(LockedAccountException lae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
			modelMap.addAttribute("message_login", "账户已锁定");
			return view("login");
		}catch(ExcessiveAttemptsException eae){
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,错误次数过多");
			modelMap.addAttribute("message_login", "用户名或密码错误次数过多");
			return view("login");
		}catch(AuthenticationException ae){
			//通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			System.out.println("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
			ae.printStackTrace();
			modelMap.addAttribute("message_login", "用户名或密码不正确");
			return view("login");
		}
		//验证是否登录成功
		if(currentUser.isAuthenticated()){
			System.out.println("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
		}else{
			token.clear();
		}
		String userNames = this.getUserName();
		List<PermissionDto> permissionDtoList = securityApplication.findPermissionDtoList();
		modelMap.addAttribute("permissionDtoList", permissionDtoList);
		return view("index",userNames);
	}

	/**
	 *    index page
	 */
	@RequestMapping(value = "/logins")
	public ModelAndView logins(ModelMap modelMap) {
		String userName = this.getUserName();
		List<PermissionDto> permissionDtoList = securityApplication.findPermissionDtoList();
		modelMap.addAttribute("permissionDtoList", permissionDtoList);
		return view("index",userName);
	}

	/**
	 * 用户登出
	 */
	@RequestMapping("/logout")
	public ModelAndView logout( ){
		SecurityUtils.getSubject().logout();
		return view("login");
	}


	@RequestMapping(value = "/userList")
	public ModelAndView userList() {

		return new ModelAndView("memberlist");
	}
	@RequestMapping(value = "/warring")
	public ModelAndView warring() {

		return new ModelAndView("/jsp/system/403");
	}

	@RequestMapping(value = "/welcome")
	public ModelAndView welcome() {

		return new ModelAndView("welcome");
	}

}
